const KoaRouter = require("@koa/router");
const ai = require("../controller/ai.controller");

const request = require("../utils/request");
const util = require("../utils/util");

// 1. 创建路由对象
const aiRouter = new KoaRouter({ prefix: "/ai" });

/**
 * 接口代理和大模型接入API接口
 */

// 项目配置
aiRouter.post("/lib/chat", ai.codeGenerate);

// aiRouter.post("/generator/AST", ai.astGenerate);

// 接口转发(get)
aiRouter.get("/proxy", async (ctx) => {
  try {
    const {
      query,
      headers: { host, origin, proxyapi, ...headers },
    } = ctx.request;
    const response = await request.get(proxyapi, query || {}, {
      headers,
    });
    if (response.data) {
      const res = JSON.parse(response.data);
      ctx.body = res;
    } else {
      ctx.body = response.data;
    }
  } catch (error) {
    util.fail(ctx, 500, error.message);
  }
});

// 接口转发(post)
aiRouter.post("/proxy", async (ctx) => {
  try {
    const {
      body,
      headers: { host, origin, proxyapi, ...headers },
    } = ctx.request;
    const response = await request.post(proxyapi, JSON.stringify(body || {}), {
      headers,
    });
    if (response.data) {
      const res = JSON.parse(response.data);
      ctx.body = res;
    } else {
      ctx.body = response.data;
    }
  } catch (error) {
    util.fail(ctx, 500, error.message);
  }
});

module.exports = aiRouter;
